package com.nineclock.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.message.dto.SysRegisterDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    SysUserMapper userMapper;
    @Autowired
    SmsServiceImpl smsService;


    @Override
    public Boolean checkExists(String mobile) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>();
        queryWrapper.eq(SysUser::getMobile, mobile);
        Integer count = userMapper.selectCount(queryWrapper);
        return count==1;
    }


    @Override
    public Long register(SysRegisterDTO sysRegisterDTO) {
        //参数校验
        if (sysRegisterDTO == null || StrUtil.isEmpty(sysRegisterDTO.getCheckcode()) || StrUtil.isEmpty(sysRegisterDTO.getMobile()) || StrUtil.isEmpty(sysRegisterDTO.getPassword())){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //验证码校验
        boolean flag = smsService.verifySmsCode(sysRegisterDTO.getMobile(), SMSConstant.SMS_TYPE_REGISTER, sysRegisterDTO.getCheckcode());
        if (!flag){
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }
        //手机号校验
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getMobile,sysRegisterDTO.getMobile());
        SysUser sysUser = userMapper.selectOne(wrapper);
        if (sysUser != null){
            throw new NcException(ResponseEnum.USER_MOBILE_EXISTS);
        }

        SysUser sysUser1 = new SysUser();
        sysUser1.setMobile(sysRegisterDTO.getMobile());
        sysUser1.setPassword(new BCryptPasswordEncoder().encode(sysRegisterDTO.getPassword()));
        sysUser1.setCreateTime(new Date());
        sysUser1.setStatus((short)0);
        userMapper.insert(sysUser1);
        //删除redis验证码
        smsService.deleteSmsCode(sysRegisterDTO.getMobile(),SMSConstant.SMS_TYPE_REGISTER);


        return sysUser1.getId();
    }
}